package com.automannn.atm_back.modules.codeGenerator.environment;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author chenkh
 * @time 2020/6/29 20:56
 */
@Component
@Slf4j
public class EnvironmentPerceptionRunner implements ApplicationRunner {
    private static final String DRIVER_CLASS_NAME = "driverClassName";
    @Autowired
    private DataSource dataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        String[] dbType = new String[1];
        String[] url = new String[1];
        if(dataSource instanceof DynamicRoutingDataSource){
            DynamicRoutingDataSource curDataSource = (DynamicRoutingDataSource)dataSource;
            curDataSource.getCurrentDataSources().entrySet().forEach(entry->{
                //todo: 多数据源的处理
                DruidDataSource realDataSource = (DruidDataSource) entry.getValue();
                dbType[0] = realDataSource.getDbType();
                url[0] =realDataSource.getUrl();
            });
        }else {
            //todo: 扩展其它数据源
        }

        String namespace = "";
        //若为数据库存储，则在这里进行判别
        if (StringUtils.isNotEmpty(dbType[0])) {
            if (dbType[0].toLowerCase().contains("mysql")) {
                EnvironmentPerception.setDatasourceType(DatasourceType.MYSQL);
                namespace = url[0].substring(url[0].lastIndexOf("/")+1,
                        url[0].indexOf("?"));
                EnvironmentPerception.setNamespace(namespace);
            } else if (dbType[0].toLowerCase().contains("postgresql")) {
                EnvironmentPerception.setDatasourceType(DatasourceType.POSTGRE_SQL);
                namespace = url[0].substring(url[0].lastIndexOf("/"));
                EnvironmentPerception.setNamespace(namespace);
            } else if (dbType[0].toLowerCase().contains("oracle")) {
                EnvironmentPerception.setDatasourceType(DatasourceType.ORACLE);
                namespace = url[0].substring(url[0].lastIndexOf("/"));
                EnvironmentPerception.setNamespace(namespace);
            } else if (dbType[0].toLowerCase().contains("sqlserver")) {
                EnvironmentPerception.setDatasourceType(DatasourceType.SQL_SERVER);
                namespace = url[0].substring(url[0].lastIndexOf("/"));
                EnvironmentPerception.setNamespace(namespace);
            } else {
                throw new RuntimeException("暂不支持mysql,pg,oracle,sqlserver数据库之外的其它数据库源.");
            }
        } else {
            log.info("未检测到数据库源信息!");
        }
    }


}
